﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EssenceFeed.Core.Helpers;
using EssenceFeed.Data.EntityModel;
using EssenceFeed.Data.Interfaces;
using EssenceFeed.Data.Repositories;
using EssenceFeed.Data.ViewModels;

namespace EssenceFeed.Areas.Administration.Controllers
{
    /// <summary>
    /// Customer Controller
    /// </summary>
    public class CustomerController : Controller
    {
        private const int DEFAULTPAGESIZE = 10;
        private readonly ICustomerRepository _customerRepository;

        /// <summary>
        /// Dependency Injection enabled constructors
        /// </summary>
        public CustomerController() : this(new CustomerRepository())
        {
        }

        /// <summary>
        /// Customer Controller Constructor
        /// </summary>
        /// <param name="customerRepository"></param>
        public CustomerController(ICustomerRepository customerRepository)
        {
            _customerRepository = customerRepository;
        }

        /// <summary>
        /// Display the listing of Customer
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(string strQuery, int? page)
        {
            IQueryable<Customer> customer = !string.IsNullOrWhiteSpace(strQuery)
                                      ? _customerRepository.FindCustomerByName(strQuery).OrderBy(d => d.CreatedDate)
                                      : _customerRepository.FindAllCustomer().OrderBy(d => d.CreatedDate);
            var paginatedNotification =
                customer.ToPagedList(page.HasValue ? page.Value - 1 : 0, DEFAULTPAGESIZE);
            return View("IndexTest",paginatedNotification);
        }

        /// <summary>
        /// Details of Customer
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Details(int? id)
        {
            if (id != null)
            {
                var customer = _customerRepository.GetCustomerById(id.Value);

                if (customer == null)
                {
                    return new FileNotFoundResult {Message = "No Customer found for that id"};
                }

                return View(new CustomerViewModel(customer));
            }

            return new FileNotFoundResult {Message = "No Customer found due to invalid notification id"};
        }

        /// <summary>
        /// Create Customer
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult Create()
        {
            var customer = new Customer();
            return View(new CustomerViewModel(customer));
        }

        /// <summary>
        /// Create Customer </summary>
        /// <param name="customer"></param>
        /// <returns></returns>
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Customer customer)
        {
            if (ModelState.IsValid)
            {
                customer.UserCreated = HttpContext.User.Identity.Name;
                customer.CreatedDate = DateTime.Now.ToSqlDateTime();
                customer.IsActive = Convert.ToBoolean(Request["IsActive"]);
                _customerRepository.Add(customer);
                _customerRepository.Save();
                return RedirectToAction("Details", new {id = customer.CustomerId});
            }

            return View(new CustomerViewModel(customer));
        }

        /// <summary>
        /// Edit Customer
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult Edit(int id)
        {
            var customer = _customerRepository.GetCustomerById(id);
            return View(new CustomerViewModel(customer));
        }

        /// <summary>
        /// Edit Customer
        /// </summary>
        /// <param name="id"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Edit(int id, FormCollection collection)
        {
            var customer = _customerRepository.GetCustomerById(id);
            if (ModelState.IsValid)
            {
                try
                {
                    customer.UserModified = HttpContext.User.Identity.Name;
                    customer.ModifiedDate = DateTime.Now;
                    UpdateModel(customer, "Customer");
                    _customerRepository.Save();
                    return RedirectToAction("Details", new {id = customer.CustomerId});
                }
                catch
                {
                    return View(new CustomerViewModel(customer));
                }
            }
            return View(new CustomerViewModel(customer));
        }

        /// <summary>
        /// Delete Customer
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult Delete(int id)
        {
            var customer = _customerRepository.GetCustomerById(id);
            return customer == null ? View("NotFound") : View(customer);
        }

        /// <summary>
        /// Delete Customer
        /// </summary>
        /// <param name="id"></param>
        /// <param name="confirmButton"></param>
        /// <returns></returns>
        [HttpPost, Authorize]
        public ActionResult Delete(int id, string confirmButton)
        {
            var customer = _customerRepository.GetCustomerById(id);

            if (customer != null)
            {
                _customerRepository.Delete(customer);
                _customerRepository.Save();
                return View("Delete");
            }
            return View("NotFound");
        }

        /// <summary>
        /// Handle Unknown Action
        /// </summary>
        /// <param name="actionName"></param>
        /// <exception cref="HttpException"></exception>
        protected override void HandleUnknownAction(string actionName)
        {
            throw new HttpException(404, "Action not found");
        }
    }
}